from . import api
from flask import jsonify,request
from app.models import *
import json,time
import app
import requests

@api.route("/")
def index():
    return '<h1>api</h1>'

# 微信首页 请求地址  api
# http://192.168.111.139:5000/api/list?appkey=&type=bookLibrary
@api.route('/list')
def book_index():
    # 定义搜索字段
    keywords = request.args.get('keywords',None)
    # 检测是否有搜索条件
    if keywords:
        # 有搜索条件,按条件搜索
        books = Books.query.filter(Books.title.contains(keywords))
    else:
        # 没搜索条件 获取所有的图书信息
        books = Books.query.all()
    # 定义空,接收获取来的信息
    data = {'result':[]}
    for x in books:
        arr = {'title':x.title,'author':x.suthor,'price':x.price,'isbn':x.isbn,'num':x.num,'image':app.SERVER_ROOT+x.image}
        data['result'].append(arr)

    # 返回json
    return jsonify(data)

# 图书详情
# http://192.168.111.139:5000/api/book/detail/9787121185632
@api.route('/book/detail/<bookid>')
def book_detail(bookid):
    # 根据书号,获取书籍信息
    book = Books.query.filter_by(isbn=bookid).first()
    # print(111111111,book,11111111)
    data = {'title':book.title,
        'isbn':book.isbn,
        'author':book.suthor,
        'image':app.SERVER_ROOT+book.image,
        'publisher':book.publisher,
        'price':book.price,
        'num':book.num,
        'summary':book.recommend,
        'authorinfo':book.authorinfo,
        'catalog':book.catalog,
        'Explain':book.explain
    }

    return jsonify(data)


# 登录注册
@api.route('/login')
def login():

    # 接受 code
    code = request.args.get('code')

    # 向微信服务器发起请求,获取openid
    # https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
    url = 'https://api.weixin.qq.com/sns/jscode2session?appid=wx858203c1df5845ac&secret=46f6f9f4cdb8de044891901696a98e09&js_code='+code+'&grant_type=authorization_code'
    # 发起请求,获取响应对象
    response = requests.get(url)

    # 获取响应结果,转dict
    res = response.json()
    print(res)
    data = request.args.to_dict()
    data.pop('code')
    # 获取openid
    data['openid'] = res['openid']


    # 判断数据库中是否已经存在
    ob = Users.query.filter_by(openid = data['openid']).first()
    if not ob:
        # 如果不存在,则添加数据
        # 存入数据库
        user = Users(**data)
        db.session.add(user)
        db.session.commit()

    # 返回数据
    data = {'error':0,'openid':res['openid']}

    return jsonify(data)

# 借阅图书
@api.route('/book/borrow',methods=['POST'])
def book_boorrw():
    try:
        # 接受小程序发送的json数据
        data = request.json   
        # 判断当前图书数量是否大于0
        book = Books.query.filter_by(isbn=data['isbn']).first()
        if book.num:
            # 存入数据库
            print(data)
            ob = bookBorrow(**data)

            db.session.add(ob)
            db.session.commit()
            # 修改当前图书 可借阅的数量
            book.num -= 1
            db.session.add(book)
            db.session.commit()

            return jsonify({'error':0,'msg':'借阅成功'})
        else:
            return jsonify({'error':1,'msg':'该书数量不足'})
    except:
        return jsonify ({'error':2,'msg':'请联系相关人员'})


# 获取当前用户的借阅图书信息
@api.route('/get')
def GetUserBorrowAll():
    # 接受openid
    openid = request.args.get('key')

    # 获取当前用户借阅的所有图书
    # borrow = bookBorrow.query.filter(bookBorrow.openid==openid,bookBorrow.isreturn!=1).all()
    borrow = bookBorrow.query.filter(bookBorrow.openid==openid,bookBorrow.isreturn != 1).all()
    result = []

    # 判断当前用户是否有借阅信息
    if borrow:
        for x in borrow:
            book = Books.query.filter_by(isbn=x.isbn).first()
            arr = {
                'borrowid':x.id,
                'title':book.title,
                'author':book.suthor,
                'price':book.price,
                'ublisher':book.publisher,
                'num':book.num,
                'image':app.SERVER_ROOT+book.image,
                'isbn':book.isbn,
                'borrowDate':x.starttime,
                'shouldBackDate':x.endtime,
            }
            result.append(arr)
    data = {'error':0,'mag':'ok','result':result}
    return jsonify(data)



@api.route('/book/haishu',methods=['POST','GET'])
def book_haishu():
    
    # 接受小程序发送的json数据
    data = request.args.get('borrowid')
    print(data)
    # 通过borrowid在表中获取实例对象
    ob = bookBorrow.query.get(data)
    print('ob',ob,'ob')
    # 给状态赋值为1,为还书状态
    ob.isreturn = 1

    # 获取当前时间戳
    # nowtime = time.time()

    # starttime = str(ob.starttime).split(' ')[0].split('-')

    # nowtimes = datetime.datetime.now()
    # nowtime = str(nowtimes).split(' ')[0].split('-')

    # readtime = 0

    # for i in range(3):
    #     if int(starttime[i]) != int(nowtime[i]):
    #         if i == 2:
    #             readtime += int(nowtime[2]) - int(starttime-2)
    #         elif i == 1:
    #             readtime += (int(nowtime[1]) - int(starttime[1]))*30
    #         elif i == 0:
    #             readtime += (int(owtime[0]) - int(starttime[0]))*365
    # ob.readtime = readtime
    # ob.endtime = nowtimes
    db.session.add(ob)
    db.session.commit()

    return ''
    # return jsonify({'error':0,'msg':'还书成功'})